from langchain_core.output_parsers import JsonOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
import os
import sys

# from prompt.reading_comprehension_analysis import READING_COMPREHENSION_ANALYSIS

OPENAI_API_KEY = "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"

READING_COMPREHENSION_ANALYSIS = """
作为一个教育分析专家，您需要对一道阅读理解题进行评估。这包括分析学生对题目的理解，为什么他们可能选择了错误的答案，以及解释正确答案的理由。此外，还需要根据学生的错误回答提出改进的建议。

阅读理解题详情如下：
- 阅读材料：{reading_material}
- 题目：{question_text}
- 正确答案：{correct_answer}
- 学生选择的答案：{student_answer}

请完成以下任务：
1. 分析学生可能选择错误答案{student_answer}的原因。
2. 提供正确答案{correct_answer}的解释，说明为什么这是正确的。
3. 根据学生的理解情况，给出针对性的建议来帮助他们提高阅读理解能力。

请使用以下JSON格式输出您的评价和建议：
{{
  "error_analysis": "学生可能选择错误答案的原因分析...",
  "correct_answer_explanation": "正确答案之所以正确的解释...",
  "suggestions": "建议"
}}
"""
os.environ["http_proxy"] = "http://127.0.0.1:10808"
os.environ["https_proxy"] = "http://127.0.0.1:10808"


def evaluate_reading_comprehension(
    reading_material: str, question_text: str, correct_answer: str, user_answer: str
):
    """
    This function evaluates a user's answer to a reading comprehension question and provides an analysis of the answer.

    Parameters:
    reading_material (str): The text that the reading comprehension question is based on.
    question_text (str): The text of the reading comprehension question.
    correct_answer (str): The correct answer to the reading comprehension question.
    user_answer (str): The user's answer to the reading comprehension question.

    Returns:
    dict: A dictionary containing the success status of the evaluation, an analysis of the user's answer, and any errors that occurred during the evaluation.
    """
    try:
        # 分析用户为什么会选错这一道题
        prompt_template = ChatPromptTemplate.from_template(
            READING_COMPREHENSION_ANALYSIS
        )
        llm = ChatOpenAI(openai_api_key=OPENAI_API_KEY)
        json_parser = JsonOutputParser()
        chain = prompt_template | llm | json_parser
        evaluation_result = chain.invoke(
            {
                "reading_material": reading_material,
                "question_text": question_text,
                "correct_answer": correct_answer,
                "student_answer": user_answer,
            }
        )
        print(evaluation_result.get("correct_answer_explanation", ""))
        print(evaluation_result.get("error_analysis", ""))
        print(evaluation_result.get("suggestions", ""))
        # 组装返回结果
        # return {
        #     "success": True,
        #     "analysis": {
        #         "error_analysis": evaluation_result.get("error_analysis", ""),
        #         "correct_answer_analysis": evaluation_result.get(
        #             "correct_answer_explanation", ""
        #         ),
        #         "suggestions": evaluation_result.get("suggestions", ""),
        #     },
        # }
    except Exception as e:
        print(e)
        # return {"success": False, "analysis": None, "error": str(e)}


if __name__ == "__main__":

    reading_material = sys.argv[1]
    question_text = sys.argv[2]
    correct_answer = sys.argv[3]
    user_answer = sys.argv[4]
    # reading_material = 'ant-housing, you couldn\'t get listed and admitted into the hospital," Kaufman said. She leaned that for the nearly 110,000 people in the US waiting for a lifesaving organ transplant, it was not just a matter of adding your name to the list. Patients must be financially secure and be able to afford transportation. What\'s more, they must find accommodations near their transplant hospital: Kaufman runs two housing locations, which allows the patients to remain close to their transplant hospital during the period of their aftercare, typically about three months at no cost. Her organization also helps donor families, which she thinks makes the whole circle complete. "One organ donor can save eight lives and then there\'s tissue and skin and eyes and blood vessels(血管) and so many other things," Kaufman said. "The donor is the whole story. Without the donor, there are no transplant centers, no transplant surgeons, no me. In my eyes, the donors are the heroes." To date, Ava\'s Heart has helped nearly 90 families with burial costs for their loved ones whose organs have saved countless lives. Kaufman also works closely with those who receive donations to build relationships with donor families and spread awareness about the importance of organ donation.'
    # question_text = "Why did Kaufman take about her memory in Paragraph 1?'A. To illustrate the significance of life.B. To recall her plain and boring daysC. To indicate her motivation for paying back.sD. To confirm her enthusiasm for the profession."
    # correct_answer = "A"
    # user_answer = "B"
    evaluate_reading_comprehension(
        reading_material, question_text, correct_answer, user_answer
    )
